package com.lagou.edu.configuration;

import com.lagou.edu.annotations.MyAutowired;
import com.lagou.edu.annotations.MyService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @Author 应癫
 * @create 2019/12/3 11:46
 */
@Component
public class LagouBean implements InitializingBean, ApplicationContextAware {

//	private ItBean itBean;

//	public void setItBean(ItBean itBean) {
//		this.itBean = itBean;
//	}

	/**
	 * 构造函数
	 */
	public LagouBean(){
		System.out.println("LagouBean 构造器...");
	}


	/**
	 * InitializingBean 接口实现
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("LagouBean afterPropertiesSet...");
	}

	public void print() {
		System.out.println("print方法业务逻辑执行");
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		//获取所有@MyService注解定义的bean
		String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(MyService.class);
		for (String names : beanNamesForAnnotation) {
			//获取所有的属性
			Object bean = applicationContext.getBean(names);
			Field[] fields = bean.getClass().getDeclaredFields();
			//判断指定的注解是否在这个元素上
			for (Field field : fields) {
				if (field.isAnnotationPresent(MyAutowired.class)) {

					field.setAccessible(true);
					try {
						field.set(bean,applicationContext.getBean(field.getType()));
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
		System.out.println("setApplicationContext....");
	}
}
